package com.xiaowu.friend.service.question.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.xiaowu.common.core.constants.Constants;
import com.xiaowu.common.core.domain.TableDataInfo;
import com.xiaowu.friend.domain.question.Question;
import com.xiaowu.friend.domain.question.dto.QuestionQueryDTO;
import com.xiaowu.friend.domain.question.es.QuestionES;
import com.xiaowu.friend.domain.question.vo.QuestionDetailVO;
import com.xiaowu.friend.domain.question.vo.QuestionVO;
import com.xiaowu.friend.elasticsearch.QuestionRepository;
import com.xiaowu.friend.manager.QuestionCacheManager;
import com.xiaowu.friend.mapper.question.QuestionMapper;
import com.xiaowu.friend.mapper.user.UserSubmitMapper;
import com.xiaowu.friend.service.question.IQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class QuestionServiceImpl implements IQuestionService {

    // 注入QuestionRepository
    @Autowired
    QuestionRepository questionRepository;

    // 注入QuestionMapper
    @Autowired
    QuestionMapper questionMapper;

    // 注入QuestionCacheManager
    @Autowired
    QuestionCacheManager questionCacheManager;

    @Autowired
    UserSubmitMapper userSubmitMapper;

    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        // 获取题目总数
        Long count = questionRepository.count();
        // 如果题目总数小于等于0，则刷新索引
        if (count <= 0) {
            refreshQuestion(); // 刷新索引
        }
        // 设置排序规则，按createTime降序排列
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        // 设置分页参数
        Pageable pageable = PageRequest
                .of(questionQueryDTO.getPageNum() - 1, questionQueryDTO.getPageSize(), sort);
        // 获取难度和关键字
        Integer difficulty = questionQueryDTO.getDifficulty();
        String keyword = questionQueryDTO.getKeyword();
        // 根据难度和关键字查询问题
        Page<QuestionES> questionESPage;
        if (difficulty == null && StrUtil.isEmpty(keyword)) {
            questionESPage = questionRepository
                    .findAll(pageable);
        } else if (difficulty == null) {
            questionESPage = questionRepository
                    .findByTitleOrContent(keyword, keyword, pageable);
        } else if (StrUtil.isEmpty(keyword)) {
            questionESPage = questionRepository
                    .findQuestionByDifficulty(difficulty, pageable);
        } else {
            questionESPage = questionRepository
                    .findByTitleOrContentAndDifficulty(keyword, keyword, difficulty, pageable);
        }
        // 获取题目总数
        Long total = questionESPage.getTotalElements();
        // 如果题目总数小于等于0，则返回空数据
        if (total <= 0) {
            return TableDataInfo.empty();
        }
        // 获取题目列表
        List<QuestionES> questionESList = questionESPage.getContent();
        // 将题目列表转换为VO列表
        List<QuestionVO> questionVOList = BeanUtil.copyToList(questionESList, QuestionVO.class);
        // 返回题目列表和总数
        return TableDataInfo.success(questionVOList, total);
    }

    @Override
    public List<QuestionVO> hotList() {
        Long total = questionCacheManager.getHostListSize();
        List<Long> hotQuestionIdList;
        if (total == null || total <= 0) {
            PageHelper.startPage(Constants.HOST_QUESTION_LIST_START, Constants.HOST_QUESTION_LIST_END);
            hotQuestionIdList = userSubmitMapper.selectHostQuestionList();
            questionCacheManager.refreshHotQuestionList(hotQuestionIdList);
        } else {
            hotQuestionIdList = questionCacheManager.getHostList();
        }
        return assembleQuestionVOList(hotQuestionIdList);
    }

    @Override
    public QuestionDetailVO detail(Long questionId) {
        // 根据题目ID查询问题
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        // 创建题目详情VO
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        // 如果题目存在，则将问题属性复制到问题详情VO中
        if (questionES != null) {
            BeanUtil.copyProperties(questionES, questionDetailVO);
            return questionDetailVO;
        }
        // 如果题目不存在，则从数据库中查询问题
        Question question = questionMapper.selectById(questionId);
        // 如果题目不存在，则返回null
        if (question == null) {
            return null;
        }
        // 刷新索引
        refreshQuestion();
        // 将题目属性复制到问题详情VO中
        BeanUtil.copyProperties(question, questionDetailVO);
        return questionDetailVO;
    }

    @Override
    public String preQuestion(Long questionId) {
        // 获取问题列表大小
        Long listSize = questionCacheManager.getListSize();
        // 如果问题列表大小为空或小于等于0，则刷新缓存
        if (listSize == null || listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        // 获取上一个问题
        return questionCacheManager.preQuestion(questionId).toString();
    }

    @Override
    public String nextQuestion(Long questionId) {
        // 获取问题列表大小
        Long listSize = questionCacheManager.getListSize();
        // 如果问题列表大小为空或小于等于0，则刷新缓存
        if (listSize == null || listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        // 获取下一个问题
        return questionCacheManager.nextQuestion(questionId).toString();
    }

    private List<QuestionVO> assembleQuestionVOList(List<Long> hotQuestionIdList) {
        if (CollectionUtil.isEmpty(hotQuestionIdList)) {
            return new ArrayList<>();
        }
        List<QuestionVO> resultList = new ArrayList<>();
        for (Long questionId : hotQuestionIdList) {
            QuestionVO questionVO = new QuestionVO();
            QuestionDetailVO detail = detail(questionId);
            questionVO.setTitle(detail.getTitle());
            resultList.add(questionVO);
        }
        return resultList;
    }

    // 刷新索引
    private void refreshQuestion() {
        // 从数据库中查询所有问题
        List<Question> questionList = questionMapper
                .selectList(new LambdaQueryWrapper<Question>());
        // 如果问题列表为空，则返回
        if (CollectionUtil.isEmpty(questionList)) {
            return;
        }
        // 将问题列表转换为ES问题列表
        List<QuestionES> questionESList = BeanUtil.copyToList(questionList, QuestionES.class);
        // 保存ES问题列表
        questionRepository.saveAll(questionESList);
    }
}
